package jp.co.sharp.android.parents.kidsguard.activity.edit;

import android.bluetooth.BluetoothAdapter;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Handler;
import android.os.Message;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.MotionEvent;
import android.view.View;
import android.widget.AbsListView;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.TextView;

import com.android.bluetooth.parentble.ParentBleTransfer;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.List;

import jp.co.sharp.android.parents.kidsguard.App;
import jp.co.sharp.android.parents.kidsguard.R;
import jp.co.sharp.android.parents.kidsguard.activity.edit.adapter.ScheduleListAdapter;
import jp.co.sharp.android.parents.kidsguard.activity.home.HomeActivity;
import jp.co.sharp.android.parents.kidsguard.activity.profile.ProfileEditActivity;
import jp.co.sharp.android.parents.kidsguard.activity.setting.PowerSettingActivity;
import jp.co.sharp.android.parents.kidsguard.activity.setting.SettingActivity;
import jp.co.sharp.android.parents.kidsguard.common.DealWithWaitingDlg;
import jp.co.sharp.android.parents.kidsguard.common.DelDeviceConfirmDlg;
import jp.co.sharp.android.parents.kidsguard.common.ProcessWarningDlg;
import jp.co.sharp.android.parents.kidsguard.contants.Constants;
import jp.co.sharp.android.parents.kidsguard.contants.PageSerialNumConstants;
import jp.co.sharp.android.parents.kidsguard.contants.RequestMethodConstants;
import jp.co.sharp.android.parents.kidsguard.contants.RequestReceiverConstants;
import jp.co.sharp.android.parents.kidsguard.dto.BluetoothReceiverDto;
import jp.co.sharp.android.parents.kidsguard.dto.ScheduleDetailDto;
import jp.co.sharp.android.parents.kidsguard.dto.ScheduleDto;
import jp.co.sharp.android.parents.kidsguard.entity.KidInfoEntity;
import jp.co.sharp.android.parents.kidsguard.thread.BusinessThread;

public class ScheduleListActivity extends AppCompatActivity {

    private final static int SCHEDULE_EDIT_CODE = 1000;

    private final static int REFRESH = 0;

    private final static int PUSH_UP = 1;

    private final static int PUSH_DOWN = 2;
    private static final String TAG = "TAG";
    public ParentBleTransfer mParentBleTransfer;
    SimpleDateFormat sdf=new SimpleDateFormat("yyyy-MM-dd");
    private App mApp;
    private ListView mScheduleListLv;
    private TextView mAddTv;
    private ImageView mBackIv;
    private Boolean mOnSyncResultFlag = false;
    private Boolean mGetScheduleFlag = false;
    private List<ScheduleDto> mList = new ArrayList<>();
    private String mSearchDay;
    private int mType;
    private String mMode ;
    private int mScheduleId;
    private String mScheduleDate;
    private DealWithWaitingDlg mDealWithWaitingDlg;
    // 編集を再開しています...
    private boolean mEditReopening = false;
    /**
     * Dialog閉じる
     */
    Handler handler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            if (null != mDealWithWaitingDlg && mDealWithWaitingDlg.isShowing()) {
                mDealWithWaitingDlg.dismiss();
            }
        }
    };
    private KidInfoEntity mKidInfoEntity;
    private boolean mScreenOperate = false;
    private boolean mUnReceiver = true;
    // ページジャンプ
    private boolean mPageJumpFlag = false;
    /**
     * BroadcastReceiver
     */
    private final BroadcastReceiver receiver = new BroadcastReceiver() {
        @Override
        public void onReceive(Context context, Intent intent) {
            String action = intent.getAction();
            if (RequestReceiverConstants.RECEIVER_BLUETOOTH_LISTENER_DATA_CHANGED.equals(action)) {
                Log.i(TAG, "ScheduleListActivity_receiver_RECEIVER_BLUETOOTH_LISTENER_DATA_CHANGED");
                BluetoothReceiverDto bluetoothReceiverDto = (BluetoothReceiverDto) intent.getSerializableExtra(RequestReceiverConstants.RECEIVER_KEY);
                try {
                    JSONObject resp = new JSONObject(bluetoothReceiverDto.getRetStr());
                    String method = resp.getString("method");

                    if (null != method) {
                        if (RequestMethodConstants.METHOD_GET_SCHEDULES.equals(method)) {
                            JSONArray data = resp.getJSONArray("data");
                            Log.i(TAG, "ScheduleListActivity_receiver_RECEIVER_BLUETOOTH_LISTENER_DATA_CHANGED_getSchedules:"+data.toString());
                            toList(data);
                            mScheduleListLv.setAdapter(new ScheduleListAdapter(ScheduleListActivity.this,R.layout.schedule_list,mList,
                                    new ScheduleListAdapter.OnClickItemListenter(){
                                        @Override
                                        public void chooseItemClick(ScheduleDetailDto object, View view) {
                                            mMode = "EDIT";
                                            mScheduleId = object.getId();
                                            mScheduleDate = object.getDate();
                                            if (mScheduleId != -666){
                                                String message = "キッズケータイから情報を取得しています...";
                                                mDealWithWaitingDlg = new DealWithWaitingDlg(ScheduleListActivity.this, R.style.commonDlg, message, true);
                                                mDealWithWaitingDlg.show();
                                                sendGetLeftSpaceToKid();
                                            } else {
                                                Log.i(TAG,"点击到了 ‘予定なし’ 不做处理");
                                            }
                                        }
                                    }));
                            mAddTv.bringToFront();
                            for ( int i=0;i<mList.size();i++ ) {
                                if (mSearchDay.equals(mList.get(i).getDate())){
                                    if (mType == REFRESH){
                                        mScheduleListLv.setSelectionFromTop(i,0);
                                        break;
                                    } else if (mType == PUSH_UP){
                                        mScheduleListLv.setSelectionFromTop(i-2,0);
                                        break;
                                    }else if (mType == PUSH_DOWN){
                                        mScheduleListLv.setSelectionFromTop(i,0);
                                        break;
                                    }
                                }
                            }
                            handler.sendEmptyMessage(0);
                        } else if (RequestMethodConstants.METHOD_GET_OPERATING_STATE.equals(method)) {
                            JSONObject data = resp.getJSONObject("data");
                            Log.i(TAG, "ScheduleListActivity_receiver_RECEIVER_BLUETOOTH_LISTENER_DATA_CHANGED_getOperatingState:"+data.toString());
                            if (Constants.IS_USING_OK.equals(data.getString("state"))) {
                                sendEnterToKid();
                            }else {
                                handler.sendEmptyMessage(0);
                                String message = "別のスマートフォンから操作中のため、設定を変更できません。";
                                ProcessWarningDlg processWarringDlg = new ProcessWarningDlg(ScheduleListActivity.this, R.style.commonDlg, message);
                                processWarringDlg.show();
                                processWarringDlg.setOnOperateSetListener(new ProcessWarningDlg.OnOperateSetListener() {
                                    @Override
                                    public void onOperateSet() {
                                        processWarringDlg.dismiss();
                                        // ページジャンプ
                                        mPageJumpFlag = true;
                                        ScheduleListActivity.this.finish();
                                    }
                                });
                            }
                        } else if (RequestMethodConstants.METHOD_ON_SYNC_RESULT.equals(method)) {
                            Log.i(TAG, "ScheduleListActivity_receiver_RECEIVER_BLUETOOTH_LISTENER_DATA_CHANGED_onSyncResult");
                            if (Constants.ON_SYNC_RESULT.equals(resp.getString("result"))) {
//                                new PowerSettingThread(5).start();
                            }else {
                                handler.sendEmptyMessage(0);
                                String message = "キッズケータイへ反映できませんでした";
                                ProcessWarningDlg processWarringDlg = new ProcessWarningDlg(ScheduleListActivity.this, R.style.commonDlg, message);
                                processWarringDlg.show();
                                processWarringDlg.setOnOperateSetListener(new ProcessWarningDlg.OnOperateSetListener() {
                                    @Override
                                    public void onOperateSet() {
                                        processWarringDlg.dismiss();
                                    }
                                });
                            }
                        } else if (RequestMethodConstants.METHOD_GET_LEFTSPACE.equals(method)) {
                            Log.i(TAG, "ScheduleListActivity_receiver_RECEIVER_BLUETOOTH_LISTENER_DATA_CHANGED_getLeftSpace");
                            JSONObject data = resp.getJSONObject("data");
                            String size = data.getString("size");
                            if (Double.parseDouble(size) >= 5242880) {
                                if ("ADD".equals(mMode)){
                                    mPageJumpFlag = true;
                                    Intent intent1 = new Intent();
                                    intent1.setClass(ScheduleListActivity.this, ScheduleEditActivity.class);
                                    intent1.putExtra("MODE", mMode);
                                    startActivityForResult(intent1,SCHEDULE_EDIT_CODE);
                                } else {
                                    sendGetScheduleDetailsToKid();
                                }


                            }else {
                                //TODO

                            }
                        } else if (RequestMethodConstants.METHOD_GET_SCHEDULES_DETAILS.equals(method)) {
                            JSONObject data = resp.getJSONObject("data");
                            Log.i(TAG, "ScheduleListActivity_receiver_RECEIVER_BLUETOOTH_LISTENER_DATA_CHANGED_getScheduleDetails:"+data.toString());
                            ScheduleDetailDto scheduleDetailDto = new ScheduleDetailDto();
                            scheduleDetailDto.setId(data.getInt("id"));
                            scheduleDetailDto.setTitle(data.getString("title"));
                            scheduleDetailDto.setStart(data.getString("start"));
                            scheduleDetailDto.setEnd(data.getString("end"));
                            scheduleDetailDto.setMemo(data.getString("memo"));
                            scheduleDetailDto.setAllDay(data.getInt("allDay"));
                            scheduleDetailDto.setRepeat(data.getInt("repeat"));
                            scheduleDetailDto.setAlarm(data.getInt("alarm"));
                            scheduleDetailDto.setDate(mScheduleDate);
                            handler.sendEmptyMessage(0);
                            mPageJumpFlag = true;
                            Intent intent1 = new Intent();
                            intent1.setClass(ScheduleListActivity.this, ScheduleEditActivity.class);
                            intent1.putExtra("MODE", mMode);
                            intent1.putExtra("INFO",scheduleDetailDto);
                            startActivityForResult(intent1,SCHEDULE_EDIT_CODE);
                        }else if (RequestMethodConstants.METHOD_ON_OPERATE_INTERRUPT.equals(method)){
                            Log.i(TAG, "ScheduleListActivity_receiver_RECEIVER_BLUETOOTH_LISTENER_DATA_CHANGED_onOperateInterrupt");
                            String message = "キッズケータイが操作されました。編集を中断します。";
                            ProcessWarningDlg processWarringDlg = new ProcessWarningDlg(ScheduleListActivity.this, R.style.commonDlg, message);
                            processWarringDlg.show();
                            processWarringDlg.setOnOperateSetListener(new ProcessWarningDlg.OnOperateSetListener() {
                                @Override
                                public void onOperateSet() {
                                    processWarringDlg.dismiss();
                                    back();
                                }
                            });
                        }
                    }
                } catch (JSONException e) {
                     Log.e(TAG,e.getMessage());
                }

            } else if (RequestReceiverConstants.RECEIVER_BLUETOOTH_WRITE_DATA_CHANGED.equals(action)) {
                //isFinish
                Log.i(TAG, "ScheduleListActivity_receiver_RECEIVER_BLUETOOTH_WRITE_DATA_CHANGED");
                BluetoothReceiverDto bluetoothReceiverDto = (BluetoothReceiverDto) intent.getSerializableExtra(RequestReceiverConstants.RECEIVER_KEY);
                if (bluetoothReceiverDto.isFinished()) {
                    if (mGetScheduleFlag) {
                        mGetScheduleFlag = false;
                        if (!mScreenOperate){
                            sendGetScheduleListToKid(REFRESH);
                        }else {
                            mEditReopening = false;
                            mScreenOperate = false;
                            handler.sendEmptyMessage(0);
                        }
                    }
                    if (mOnSyncResultFlag) {
                        mOnSyncResultFlag = false;
                        if (!mScreenOperate){
                            back();
                        }
                    }
                }

            }
        }
    };
    // システムホームプレス
    private boolean mSystemHomeFlag = false;
    // プログラムロック
    private String mSyncLock = "syncLock";
    /**
     * システム放送
     */
    private final BroadcastReceiver systemReceiver = new BroadcastReceiver() {
        @Override
        public void onReceive(Context context, Intent intent) {
            try {
                String action = intent.getAction();
                if (Intent.ACTION_SCREEN_OFF.equals(action)) {
                    Log.i(TAG, "ScheduleListActivity_systemReceiver_ACTION_SCREEN_OFF");
                    synchronized (mSyncLock) {
                        mApp.setAppStatus(Constants.APP_STATUS_SCREEN_OFF);
                        mScreenOperate = true;
                        sendExitToKid();
                    }
                } else if (Intent.ACTION_USER_PRESENT.equals(action)) {
                    Log.i(TAG, "ScheduleListActivity_systemReceiver_ACTION_USER_PRESENT");
                    synchronized (mSyncLock) {
                        mApp.setAppStatus(Constants.APP_STATUS_USER_PRESENT);
                        if (!mPageJumpFlag) {
                            String message = "編集を再開しています...";
                            mDealWithWaitingDlg = new DealWithWaitingDlg(ScheduleListActivity.this, R.style.commonDlg, message, false);
                            mDealWithWaitingDlg.show();
                            mScreenOperate = true;
                            mEditReopening = true;
                            sendIsUsingToKid();
                            // ブロードキャストの再登録
                            unregisterReceiver(systemReceiver);
                            initReceiver();
                        }
                    }
                } else if (Intent.ACTION_CLOSE_SYSTEM_DIALOGS.equals(action)) {
                    Log.i(TAG, "ScheduleListActivity_systemReceiver_ACTION_CLOSE_SYSTEM_DIALOGS");
                    synchronized (mSyncLock) {
                        mApp.setAppStatus(Constants.APP_STATUS_CLOSE_SYSTEM_DIALOGS);
                        mSystemHomeFlag = true;
                        mScreenOperate = true;
                        sendExitToKid();
                    }
                } else if (RequestReceiverConstants.RECEIVER_BLUETOOTH_CONNECT_STATE_CHANGED.equals(action)) {
                    Log.i(TAG, "ScheduleListActivity_receiver_RECEIVER_BLUETOOTH_CONNECT_STATE_CHANGED");
                    BluetoothReceiverDto bluetoothReceiverDto = (BluetoothReceiverDto) intent.getSerializableExtra(RequestReceiverConstants.RECEIVER_KEY);
                    String macAddress = bluetoothReceiverDto.getAddress();
                    if (((App)getApplication()).isMimamoriCheck(macAddress)) {
                        ((App)getApplication()).addmLsIsMimamori(macAddress);
                        sendExitToKid();
                        mPageJumpFlag = true;
                        Intent intent1 = new Intent();
                        intent1.setAction(Constants.ACTION_IS_MIMAMORI);
                        intent1.setClass(ScheduleListActivity.this, HomeActivity.class);
                        startActivity(intent1);
                    } else {
                        mKidInfoEntity.setBtConnStatus(Constants.DEVICE_DISCONNECTION_SUCCESS);
                        ((App)getApplication()).updateKidInfo(mKidInfoEntity);

                        String message = mKidInfoEntity.getKidName() + "と切断されました。編集を中断します。";
                        ProcessWarningDlg processWarringDlg = new ProcessWarningDlg(ScheduleListActivity.this, R.style.commonDlg, message);
                        processWarringDlg.show();
                        processWarringDlg.setOnOperateSetListener(new ProcessWarningDlg.OnOperateSetListener() {
                            @Override
                            public void onOperateSet() {
                                processWarringDlg.dismiss();
                                mPageJumpFlag = true;
                                Intent intent1 = new Intent();
                                intent1.setClass(ScheduleListActivity.this, SettingActivity.class);
                                startActivity(intent1);
                            }
                        });
                    }
                }
            } catch (Exception e) {
                Log.e(TAG, e.getMessage());
            }
        }
    };

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        Log.i(TAG, "ScheduleListActivity_onCreate");
        setContentView(R.layout.activity_schedule_list);
        mApp = (App)getApplication();
        mounted();
        initReceiver();
        init();
    }

    @Override
    public void onBackPressed() {
        sendExitToKid();
    }

    @Override
    protected void onStart() {
        super.onStart();
        Log.i(TAG, "ScheduleListActivity_onStart");
        mApp.setAppStatus(Constants.APP_STATUS_INIT);
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent intent) {
        super.onActivityResult(requestCode, resultCode, intent);
        Log.i(TAG, "ScheduleListActivity_onActivityResult");
        initReceiver();
        String message = "キッズケータイから情報を取得しています...";
        mDealWithWaitingDlg = new DealWithWaitingDlg(ScheduleListActivity.this, R.style.commonDlg, message, true);
        mDealWithWaitingDlg.show();
        sendGetScheduleListToKid(REFRESH);

    }

    @Override
    protected void onRestart() {
        super.onRestart();
        Log.i(TAG, "ScheduleListActivity_onRestart");
        synchronized (mSyncLock) {
            if (mSystemHomeFlag) {
                if ((mApp.getAppStatus() != Constants.APP_STATUS_USER_PRESENT)&&(!mEditReopening)) {
                    String message = "編集を再開しています...";
                    mDealWithWaitingDlg = new DealWithWaitingDlg(ScheduleListActivity.this, R.style.commonDlg, message, false);
                    mDealWithWaitingDlg.show();
                    mScreenOperate = true;
                    mEditReopening = true;
                    sendIsUsingToKid();
                    // ブロードキャストの再登録
                    unregisterReceiver(systemReceiver);
                    initReceiver();
                }
                mSystemHomeFlag = false;
            }
        }

    }

    @Override
    protected void onStop() {
        super.onStop();
        Log.i(TAG, "ScheduleListActivity_onStop");
        if (!mUnReceiver) {
            synchronized (mSyncLock) {
                try {
                    unregisterReceiver(receiver);
                } catch (IllegalArgumentException e) {
                    if (e.getMessage().contains("Receiver not registered")) {
                        // Ignore this exception. This is exactly what is desired
                        Log.e(TAG, e.getMessage());
                    } else {
                        // unexpected, re-throw
                        Log.e(TAG, e.getMessage());
                    }
                }
                if (mPageJumpFlag) {
                    try {
                        unregisterReceiver(systemReceiver);
                    } catch (IllegalArgumentException e) {
                        if (e.getMessage().contains("Receiver not registered")) {
                            // Ignore this exception. This is exactly what is desired
                            Log.e(TAG, e.getMessage());
                        } else {
                            // unexpected, re-throw
                            Log.e(TAG, e.getMessage());
                        }
                    }
                    mPageJumpFlag = false;
                }
                mUnReceiver = true;
            }
        }

    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        Log.i(TAG, "ScheduleListActivity_onDestroy");
        if (!mUnReceiver) {
            synchronized (mSyncLock) {
                try {
                    unregisterReceiver(receiver);
                } catch (IllegalArgumentException e) {
                    if (e.getMessage().contains("Receiver not registered")) {
                        // Ignore this exception. This is exactly what is desired
                        Log.e(TAG, e.getMessage());
                    } else {
                        // unexpected, re-throw
                        Log.e(TAG, e.getMessage());
                    }
                }
                if (mPageJumpFlag) {
                    try {
                        unregisterReceiver(systemReceiver);
                    } catch (IllegalArgumentException e) {
                        if (e.getMessage().contains("Receiver not registered")) {
                            // Ignore this exception. This is exactly what is desired
                            Log.e(TAG, e.getMessage());
                        } else {
                            // unexpected, re-throw
                            Log.e(TAG, e.getMessage());
                        }
                    }
                    mPageJumpFlag = false;
                }
                mUnReceiver = true;
            }
        }
    }

    private  void mounted(){
        Log.i(TAG, "ScheduleListActivity_mounted");
        mScheduleListLv = (ListView)findViewById(R.id.scheduleList);
        mAddTv = (TextView)findViewById(R.id.textViewAdd);
        mAddTv.bringToFront();
        mBackIv= (ImageView)findViewById(R.id.imageViewBack);
        mKidInfoEntity = ((App)getApplication()).findKidInfoBySelect();
        TextView mKidNameTv = findViewById(R.id.textViewKidName);
        String kidNameDescribe = mKidInfoEntity.getKidName()+"のキッズケータイ";
        mKidNameTv.setText(kidNameDescribe);
        mBackIv.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                sendExitToKid();
            }
        });
        mAddTv.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                sendGetLeftSpaceToKid();
                    mMode="ADD";
            }
        });

        mScheduleListLv.setOnScrollListener(new AbsListView.OnScrollListener() {
            int lastVisibleItemPos = 0;
            @Override
            public void onScrollStateChanged(AbsListView view, int scrollState) {
                switch(scrollState) {
                    case AbsListView.OnScrollListener.SCROLL_STATE_IDLE:

                        break;
                    case AbsListView.OnScrollListener.SCROLL_STATE_TOUCH_SCROLL:

                        break;
                    case AbsListView.OnScrollListener.SCROLL_STATE_FLING:

                        break;
                    default:
                        break;
                }
            }
            @Override
            public void onScroll(AbsListView view, int firstVisibleItem, int visibleItemCount, int totalItemCount) {
                if(firstVisibleItem > lastVisibleItemPos) {
                    if(firstVisibleItem + visibleItemCount == totalItemCount
                            && totalItemCount > 0) {
                        // Dlg
                        String message = "キッズケータイから情報を取得しています...";
                        mDealWithWaitingDlg = new DealWithWaitingDlg(ScheduleListActivity.this, R.style.commonDlg, message, true);
                        mDealWithWaitingDlg.show();
                        sendGetScheduleListToKid(PUSH_UP);
                    }
                }else if(firstVisibleItem < lastVisibleItemPos) {
                    if(firstVisibleItem  == 0) {
                        // Dlg
                        String message = "キッズケータイから情報を取得しています...";
                        mDealWithWaitingDlg = new DealWithWaitingDlg(ScheduleListActivity.this, R.style.commonDlg, message, true);
                        mDealWithWaitingDlg.show();
                        sendGetScheduleListToKid(PUSH_DOWN);
                    }
                }
                lastVisibleItemPos = firstVisibleItem;
            }
        });


    }

    /**
     * 初期化Receiver
     */
    private void initReceiver() {
        Log.i(TAG, "ScheduleListActivity_initReceiver");
        IntentFilter filter = new IntentFilter();
        filter.addAction(Intent.ACTION_SCREEN_OFF);
        filter.addAction(Intent.ACTION_USER_PRESENT);
        // ホームボタン
        filter.addAction(Intent.ACTION_CLOSE_SYSTEM_DIALOGS);
        // Bluetooth
        filter.addAction(RequestReceiverConstants.RECEIVER_BLUETOOTH_CONNECT_STATE_CHANGED);
        filter.addAction(RequestReceiverConstants.RECEIVER_BLUETOOTH_LISTENER_DATA_CHANGED);
        //isFinish
        filter.addAction(RequestReceiverConstants.RECEIVER_BLUETOOTH_WRITE_DATA_CHANGED);
        registerReceiver(receiver, filter);
        registerReceiver(systemReceiver, filter);
        this.mParentBleTransfer = ((App) getApplication()).getmParentBleTransfer();
        mUnReceiver = false;
    }

    /**
     *
     */
    private void init() {
        Log.i(TAG, "ScheduleListActivity_init");
        // Dlg
        String message = "キッズケータイから情報を取得しています...";
        mDealWithWaitingDlg = new DealWithWaitingDlg(ScheduleListActivity.this, R.style.commonDlg, message, true);
        mDealWithWaitingDlg.show();
        //is using
        sendIsUsingToKid();

    }

    /**
     *  getScheduleDetails to  kid
     */
    public void sendGetScheduleDetailsToKid(){
        Log.i(TAG, "ScheduleListActivity_sendGetScheduleDetailsToKid");
        JSONObject jsonData=new JSONObject();
        try {
            jsonData.put("method","getScheduleDetails");
            JSONObject jsonData2=new JSONObject();
            jsonData2.put("id",mScheduleId);
            jsonData2.put("date",mScheduleDate);
            jsonData.put("data",jsonData2);
            new BusinessThread(Constants.SEND_KID_GET_INFO,
                    mParentBleTransfer,
                    mKidInfoEntity,
                    jsonData,
                    PageSerialNumConstants.PAGE_SERIAL_SCHEDULE).start();
        } catch (JSONException e) {
             Log.e(TAG,e.getMessage());
        }

    }

    /**
     *  is using
     */
    public void sendIsUsingToKid()  {
        Log.i(TAG, "ScheduleListActivity_sendIsUsingToKid");
        try{
            JSONObject jsonObject = new JSONObject();
            jsonObject.put("method","getOperatingState");
            jsonObject.put("data",JSONObject.NULL);
            new BusinessThread(Constants.SEND_KID_IS_USING,
                    mParentBleTransfer,
                    mKidInfoEntity,
                    jsonObject,
                    PageSerialNumConstants.PAGE_SERIAL_SELF_INFO).start();
        }catch (JSONException e){
             Log.e(TAG,e.getMessage());
        }catch (Exception e){
             Log.e(TAG,e.getMessage());
        }
    }

    /**
     * enter
     */
    public void sendEnterToKid(){
        Log.i(TAG, "ScheduleListActivity_sendEnterToKid");
        mGetScheduleFlag = true;
        new BusinessThread(Constants.SEND_KID_ENTER,
                mParentBleTransfer,
                mKidInfoEntity,
                null,
                PageSerialNumConstants.PAGE_SERIAL_SCHEDULE).start();
    }

    /**
     * exit
     */
    public void sendExitToKid(){
        Log.i(TAG, "ScheduleListActivity_sendExitToKid");
        mOnSyncResultFlag = true;
        new BusinessThread(Constants.SEND_KID_EXIT,
                mParentBleTransfer,
                mKidInfoEntity,
                null,
                PageSerialNumConstants.PAGE_SERIAL_SCHEDULE).start();
    }

    /**
     * getLeftSpace
     */
    public void sendGetLeftSpaceToKid(){
        Log.i(TAG, "ScheduleListActivity_sendGetLeftSpaceToKid");
        try {
            JSONObject jsonData = new JSONObject();
            jsonData.put("method", "getLeftSpace");
            jsonData.put("data", JSONObject.NULL);
            new BusinessThread(Constants.SEND_KID_GET_INFO,
                    mParentBleTransfer,
                    mKidInfoEntity,
                    jsonData,
                    PageSerialNumConstants.PAGE_SERIAL_SCHEDULE).start();
        }catch (JSONException e){
             Log.e(TAG,e.getMessage());
        }
    }

    /**
     *
     */
    public void  sendGetScheduleListToKid(int pType){
        Log.i(TAG, "ScheduleListActivity_sendGetScheduleListToKid");
        try {
            this.mType=pType;
            JSONObject jsonData = new JSONObject();
            jsonData.put("method", "getSchedules");
            JSONObject insertData = new JSONObject();
            insertData.put("type", pType);
            if (pType == REFRESH){
                insertData.put("date", sdf.format(new Date()));
                mSearchDay = sdf.format(new Date());
            }else if (pType == PUSH_UP){
                insertData.put("date", mList.get(mList.size()-1).getDate());
                mSearchDay = mList.get(mList.size()-1).getDate();
            }else if (pType == PUSH_DOWN){
                insertData.put("date", mList.get(0).getDate());
                mSearchDay = mList.get(0).getDate();
            }
            jsonData.put("data", insertData);
            new BusinessThread(Constants.SEND_KID_GET_INFO,
                    mParentBleTransfer,
                    mKidInfoEntity,
                    jsonData,
                    PageSerialNumConstants.PAGE_SERIAL_SCHEDULE).start();
        }catch (JSONException e){
             Log.e(TAG,e.getMessage());
        }
    }

    private void back() {
        Log.i(TAG, "ScheduleListActivity_back");
        mPageJumpFlag = true;
        Intent intent = new Intent();
        intent.setClass(this, EditActivity.class);
        startActivity(intent);
    }

    private void toList(JSONArray data){
        Log.i(TAG, "ScheduleListActivity_toList");
        try{
            List<String> dateList = new ArrayList<>();
            Date date = sdf.parse(mSearchDay);
            Calendar c = Calendar.getInstance();

            if (mType == REFRESH){
                c.setTime(date);
                c.add(Calendar.DATE, -2);
                dateList.add(sdf.format(c.getTime()));
                c = Calendar.getInstance();
                c.setTime(date);
                c.add(Calendar.DATE, -1);
                dateList.add(sdf.format(c.getTime()));
                dateList.add(mSearchDay);
                for (int i = 1;i<=17;i++){
                    c = Calendar.getInstance();
                    c.setTime(date);
                    c.add(Calendar.DATE, i);
                    dateList.add(sdf.format(c.getTime()));
                }
            } else if (mType == PUSH_UP){
                for (int i = 1;i<=20;i++){
                    c = Calendar.getInstance();
                    c.setTime(date);
                    c.add(Calendar.DATE, i);
                    dateList.add(sdf.format(c.getTime()));
                }
            }else if (mType == PUSH_DOWN){
                for (int i = 20;i>=1;i--){
                    c = Calendar.getInstance();
                    c.setTime(date);
                    c.add(Calendar.DATE, -i);
                    String a =sdf.format(c.getTime());
                    dateList.add(a);
                }
            }
            List<ScheduleDto> list = new ArrayList<>();
            for (int i =0;i<data.length();i++){
                ScheduleDto scheduleDto = new ScheduleDto();
                if (data.getJSONObject(i).isNull("data")){
                    List<ScheduleDetailDto> list2 = new ArrayList<>();
                    ScheduleDetailDto scheduleDetailDto =new ScheduleDetailDto();
                    scheduleDetailDto.setTitle("予定なし");
                    scheduleDetailDto.setId(-666);
                    list2.add(scheduleDetailDto);
                    scheduleDto.setData(list2);
                }else {
                    JSONArray data2 = data.getJSONObject(i).getJSONArray("data");
                    List<ScheduleDetailDto> list2 = new ArrayList<>();
                    for (int y=0;y<data2.length();y++){
                        ScheduleDetailDto scheduleDetailDto =new ScheduleDetailDto();
                        scheduleDetailDto.setDate(data.getJSONObject(i).getString("date"));
                        scheduleDetailDto.setId(data2.getJSONObject(y).getInt("id"));
                        scheduleDetailDto.setTitle(data2.getJSONObject(y).getString("title"));
                        scheduleDetailDto.setStart(data2.getJSONObject(y).getString("start"));
                        scheduleDetailDto.setEnd(data2.getJSONObject(y).getString("end"));
                        list2.add(scheduleDetailDto);
                    }
                    scheduleDto.setData(list2);
                }
                scheduleDto.setHoliday(data.getJSONObject(i).getString("holiday"));
                scheduleDto.setDate(data.getJSONObject(i).getString("date"));
                list.add(scheduleDto);
            }

            List<ScheduleDto> resultList = new ArrayList<>();
            for (int y=0;y<dateList.size();y++){
                ScheduleDto scheduleDto = new ScheduleDto();
                boolean flag = true;
                for (ScheduleDto item : list) {
                    if (dateList.get(y).equals(item.getDate())){
                        scheduleDto=item;
                        flag=false;
                    }
                }
                if (flag){
                    List<ScheduleDetailDto> list2 = new ArrayList<>();
                    ScheduleDetailDto scheduleDetailDto =new ScheduleDetailDto();
                    scheduleDetailDto.setTitle("予定なし");
                    scheduleDetailDto.setId(-666);
                    list2.add(scheduleDetailDto);
                    scheduleDto.setData(list2);
                    scheduleDto.setHoliday(null);
                    scheduleDto.setDate(dateList.get(y));
                }
                resultList.add(scheduleDto);
            }

            /**
             *
             */
            if (this.mList.size() != 0){
                List<ScheduleDto> listNew  = new ArrayList<>();
                int compareTo = sdf.parse(this.mList.get(0).getDate()).compareTo(sdf.parse(resultList.get(0).getDate()));
                if (compareTo == -1 ){
                    listNew.addAll(this.mList);
                    listNew.addAll(resultList);
                }else {
                    listNew.addAll(resultList);
                    listNew.addAll(this.mList);
                }
                this.mList = listNew;
            }else {
                this.mList = resultList;
            }
        }catch (JSONException e){
             Log.e(TAG,e.getMessage());
        } catch (Exception e){
             Log.e(TAG,e.getMessage());
        }
    }
}
